import json
import requests
# from main.monitor.workerstatus import QueryOBSWorker

class MetricsHandler:
    def __init__(self):
        self.data_list = {"gauge":[],"counter":[]}
        self.data_type = {}
    

    def get_metrics(self, host_ip):
        url = "http://{}:9100/metrics".format(host_ip)
        headers = {'Content-type':'text/plain'}
        try:
            # print(url)
            r=requests.get(url = url,headers = headers, timeout=5)
            
            # print(r.text)
        except Exception as e:
            print(e)
            print("except occured. %s"  % host_ip)
            return
        self.parse_metrics(r.text)

    def parse_metrics(self,metrics_text):
        metrics_text_lines = metrics_text.splitlines()
        # print(len(metrics_text_lines))
        for metrics_line in metrics_text_lines:
            # print(metrics_line)
            if metrics_line.startswith('# TYPE'):
                metrics_type = metrics_line.split(' ')[3]
                data_name =  metrics_line.split(' ')[2]
                # print("type %s  name %s" %(metrics_type, data_name))
                self.data_type[data_name]=metrics_type
            elif metrics_line.startswith("# HELP"):
                continue
            else:
                bracket_pos = metrics_line.find("{")
                if bracket_pos == -1:
                    data_name = metrics_line.split(" ")[0]
                else:
                    data_name = metrics_line.split("{")[0]
                # print("name %s" %(data_name))
                if data_name not in self.data_type.keys():
                    continue
                if self.data_type[data_name] == "gauge":
                    self.data_list["gauge"].append(metrics_line.split(" ")[0])
                elif self.data_type[data_name] == "counter":
                    self.data_list["counter"].append(metrics_line.split(" ")[0])

    def save(self, host_ip):
        file_name = host_ip + "data_list.json"
        with open(file_name, "w") as data_list_file:
            json.dump(self.data_list, data_list_file)




# data_list = {"gauge":[],"counter":[]}
# data_type = {}
# query_obs_worker = QueryOBSWorker()
# def get_metrics(host_ip):
#     url = "http://{}:9100/metrics".format(host_ip)
#     headers = {'Content-type':'text/plain'}
#     try:
#         print(url)
#         r=requests.get(url = url,headers = headers, timeout=5)
        
#         # print(r.text)
#     except Exception as e:
#         print(e)
#         print("except occured. %s"  % host_ip)
#         return
#     parse_metrics_type(r.text)
#     parse_metrics_text(r.text)


# def parse_metrics_type(metrics_text):
#     metrics_text_lines = metrics_text.splitlines()
#     print(len(metrics_text_lines))
#     for metrics_line in metrics_text_lines:
#         print(metrics_line)
#         if metrics_line.startswith('# TYPE'):
#             metrics_type = metrics_line.split(' ')[3]
#             data_name =  metrics_line.split(' ')[2]
#             print("type %s  name %s" %(metrics_type, data_name))
#             data_type[data_name]=metrics_type

# def parse_metrics_text(metrics_text):
#     metrics_text_lines = metrics_text.splitlines()
#     print(len(metrics_text_lines))
#     for metrics_line in metrics_text_lines:
#         print(metrics_line)
#         if metrics_line.startswith('# TYPE') or metrics_line.startswith("# HELP"):
#             continue
#         else:
#             bracket_pos = metrics_line.find("{")
#             if bracket_pos == -1:
#                 data_name = metrics_line.split(" ")[0]
#             else:
#                 data_name = metrics_line.split("{")[0]
#             print("name %s" %(data_name))
#             if data_name not in data_type.keys():
#                 continue
#             if data_type[data_name] == "gauge":
#                 data_list["gauge"].append(metrics_line.split(" ")[0])
#             elif data_type[data_name] == "counter":
#                 data_list["counter"].append(metrics_line.split(" ")[0])
    


# def get_metrics_from_obs_worker():
#     obs_workers_ip = query_obs_worker.get_all_worker_list()
#     for arch, arch_ip_list in obs_workers_ip.items():
#         for ip in arch_ip_list:
#             ret = get_metrics(ip)


# def read_file():
#     with open("metrics_list.json", "r") as metrics_list_file:
#         metrics_list = json.load(metrics_list_file)
#         data_list = {"gauge":[], "counter":[]}
#         with open("metrics.txt", "r") as metrics_file:
#             datas = metrics_file.readlines()
#             for data in datas:
#                 first_bracket_pos = data.find("{")
#                 if first_bracket_pos == -1 :
#                     metrics_name =  data.strip()
#                 else:
#                     matircs_name = data.split('{')[0]
#                 print(matircs_name)
#                 if matircs_name in metrics_list["gauge"]:
#                     data_list["gauge"].append(data.strip())
#                 elif matircs_name in metrics_list["counter"]:
#                     data_list["counter"].append(data.strip())
#                 else:
#                     print("%s is invalid" % data)

#         with open("data_list.json", "w") as data_list_file:
#             json.dump(data_list, data_list_file)


# if __name__ == "__main__":
#     #read_file()
#     get_metrics_from_obs_worker()
#     print(data_list)
#     print(data_type)
#     with open("data_list.json", "w") as data_list_file:
#             json.dump(data_list, data_list_file)
